package org.lc.oauth.config;

import org.lc.oauth.vo.LcUserDetails;
import org.lc.oauth.util.OAuth2EndpointUtils;
import org.lc.platform.base.constant.AuthConstant;
import org.lc.platform.boot.util.LcWebUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.token.JwtEncodingContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;

import java.util.Collections;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * JWT 自定义字段配置
 *
 * @author haoxr
 * @since 3.0.0
 */
@Configuration
public class JwtTokenCustomizerConfig {

    /**
     * JWT 自定义字段
     */
    @Bean
    public OAuth2TokenCustomizer<JwtEncodingContext> jwtTokenCustomizer() {
        return context -> {
            if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())
                && context.getPrincipal() instanceof UsernamePasswordAuthenticationToken) {

                Optional.ofNullable(context.getPrincipal().getPrincipal()).ifPresent(principal -> {
                    var claims = context.getClaims();
                    if (principal instanceof LcUserDetails userDetails) { // 系统用户添加自定义字段
                        claims.claim(AuthConstant.CLIENT_SIGN, OAuth2EndpointUtils.getClientSign(LcWebUtils.getRequest()));
                        claims.claim(AuthConstant.USER_ID, userDetails.getUserId());
                        claims.claim(AuthConstant.USER_NAME, userDetails.getUsername());
                        claims.claim(AuthConstant.NICK_NAME, userDetails.getNickName());
                        claims.claim("superAdmin", userDetails.isSuperAdmin());
                        claims.claim(AuthConstant.ROLES, userDetails.getRoles());
                        claims.claim(AuthConstant.CLIENTID, userDetails.getClientId());
                    }
                });
            }
        };
    }

}
